//
//  XSBigPictureBrowserViewController.m
//  AudioVideo
//
//  Created by xueshan1 on 2019/10/12.
//  Copyright © 2019 xueshan1. All rights reserved.
//

#import "XSBigPictureBrowserViewController.h"
#import "XSBigPictureBrowserCollectionViewCell.h"

#define kItemMargin 40

@interface XSBigPictureBrowserViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
{
    NSInteger _currentPage;
}

@property(nonatomic,strong)UICollectionView *collectionView;

@property(nonatomic,assign)BOOL hiddenBar;
@property (weak, nonatomic) IBOutlet UIView *botView;
@property (weak, nonatomic) IBOutlet UIButton *originPicBtn;
@property (weak, nonatomic) IBOutlet UILabel *originPidLabel;
@property (weak, nonatomic) IBOutlet UIButton *editBtn;
@property (weak, nonatomic) IBOutlet UIButton *doneBtn;
@property(nonatomic,strong)UIButton *navRightBtn;

@property(nonatomic,strong)NSMutableArray *selectedArray;

@end

@implementation XSBigPictureBrowserViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO];
    [self.collectionView setContentOffset:CGPointMake((kWidth+kItemMargin)*self.selectIndex, 0)];
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor blackColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    _currentPage = self.selectIndex + 1;
    self.title = [NSString stringWithFormat:@"%ld/%ld", _currentPage, self.dataArray.count];

    for (XSPhotoModel *model in self.dataArray) {
        if (model.isSelected) {
            [self.selectedArray addObject:model];
        }
    }
    [self updateDoneBtnTitle];
    [self scrollViewDidScroll:self.collectionView];// 更新rightbtn

    
    
}

- (void)setupUI{
    [self.collectionView reloadData];
    
    [_originPicBtn setTitleColor:Theme_Color forState: UIControlStateNormal];
    UIImage *normalImg = ImageName(@"zl_btn_original_circle");
    UIImage *selImg = ImageName(@"zl_btn_selected");
    [_originPicBtn setImage:normalImg forState:UIControlStateNormal];
    [_originPicBtn setImage:selImg forState:UIControlStateSelected];
    [_originPicBtn setImageEdgeInsets:UIEdgeInsetsMake(0, -5, 0, 5)];
    _originPidLabel.textColor = Theme_Color;
    
    
    [_editBtn setTitleColor:Theme_Color forState:UIControlStateNormal];
    _editBtn.hidden = !self.canEdit;
    
    [_doneBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_doneBtn setBackgroundColor:Theme_Color];
    _doneBtn.layer.cornerRadius = 2;
    _doneBtn.layer.masksToBounds = YES;
    
    _navRightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _navRightBtn.frame = CGRectMake(0, 0, 25, 25);
    [_navRightBtn setBackgroundImage:ImageName(@"zl_btn_circle") forState:UIControlStateNormal];
    [_navRightBtn setBackgroundImage:ImageName(@"zl_btn_selected") forState:UIControlStateSelected];
    [_navRightBtn addTarget:self action:@selector(navRightBtn_Click:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:_navRightBtn];
    
}
- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *fl = [[UICollectionViewFlowLayout alloc]init];
        fl.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        fl.itemSize = CGSizeMake(kWidth, kHeight );
        fl.minimumLineSpacing = kItemMargin;
        fl.minimumInteritemSpacing  = 0;
        fl.sectionInset = UIEdgeInsetsMake(0, kItemMargin/2, 0, kItemMargin/2);
        
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(-kItemMargin/2, 0, kWidth + kItemMargin, kHeight  ) collectionViewLayout:fl];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.pagingEnabled = YES;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.scrollsToTop = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerNib:[UINib nibWithNibName:@"XSBigPictureBrowserCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"cellID"];
        [self.view addSubview:_collectionView];
        [self.view bringSubviewToFront:self.botView];
    }
    return _collectionView;
}

- (NSMutableArray *)selectedArray{
    if (!_selectedArray) {
        _selectedArray = [NSMutableArray arrayWithCapacity:5];
    }
    return _selectedArray;
}

#pragma mark - collectionView
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    XSBigPictureBrowserCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellID" forIndexPath:indexPath];
    
    cell.photoModel = self.dataArray[indexPath.item];
    cell.playBtnBlack = ^(XSPhotoModel * _Nonnull photoModel) {
        //预览
        XSAVPlayerViewController *playerVC = [[XSAVPlayerViewController alloc]initWithNibName:@"XSAVPlayerViewController" bundle:nil];
        playerVC.photoModel = photoModel;
        [self presentViewController:playerVC animated:YES completion:nil];
      
    };
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    
    self.hiddenBar = !self.hiddenBar;
    
    XSPhotoModel *modle = self.dataArray[indexPath.row];
    if (modle.type == XSAssetMediaTypeVideo) {
        //->视频编辑
        
    }else{
        //->图片编辑
        
    }
    
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView == self.collectionView) {
        XSPhotoModel *model = [self getCurrentPageModel];
        
        self.title = [NSString stringWithFormat:@"%ld/%ld", _currentPage, self.dataArray.count];

        self.navRightBtn.selected = model.isSelected;
        
        [self updateDoneBtnTitle];
    }
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
//    NSLog(@"scrollViewDidEndDragging");
}

- (XSPhotoModel *)getCurrentPageModel{
    CGPoint offset = _collectionView.contentOffset;
    
    CGFloat page = offset.x/(kWidth + kItemMargin);
    if (ceilf(page) >= self.dataArray.count) {
        return nil;
    }
    NSString *str = [NSString stringWithFormat:@"%.0f", page];
    _currentPage = str.integerValue + 1;
    XSPhotoModel *model = self.dataArray[_currentPage-1];
    return model;
}

- (void)setHiddenBar:(BOOL)hiddenBar{
    _hiddenBar = hiddenBar;
    
    [self.navigationController setNavigationBarHidden:hiddenBar animated:NO];
    self.botView.hidden = hiddenBar;
    
}
- (void)updateDoneBtnTitle{
    [self.doneBtn setTitle:[NSString stringWithFormat:@"确定(%ld)",self.selectedArray.count] forState:UIControlStateNormal];

}
#pragma mark - Action
- (void)navRightBtn_Click:(UIButton *)btn{
//    btn.selected = !btn.selected;

    if (!btn.isSelected) {
        if (self.selectedArray.count >= self.maxSelectCount) {
            ShowToastLong(@"最多选择%ld个",self.maxSelectCount);

        }else{
            btn.selected = YES;
            XSPhotoModel *model = [self getCurrentPageModel];
            model.selected = YES;
            [self.selectedArray addObject:model];
        }
        
    }else{
        btn.selected = NO;
        XSPhotoModel *model = [self getCurrentPageModel];
        model.selected = NO;
        [self.selectedArray removeObject:model];
    }
 
    [self updateDoneBtnTitle];

}



- (IBAction)originPicBanAction:(UIButton *)sender {
    self.originPicBtn.selected = !self.originPicBtn.isSelected;
//    if (self.originPicBtn.selected) {
//        XSPhotoModel *model = self.dataArray[self.selectIndex];
//        [XSPhotosManager getPhotosBytesWithModel:model completion:^(NSString *photosBytes) {
//            self.originPidLabel.text = [NSString stringWithFormat:@"(%@)", photosBytes];
//        }];
//
//    }else{
//        self.originPidLabel.text = @"";
//    }
    
}

- (IBAction)editBtnAction:(id)sender {
    XSImageEditViewController *editVC = [[XSImageEditViewController alloc] initWithNibName:@"XSImageEditViewController" bundle:nil];
    editVC.photoModel = [self.selectedArray firstObject];
    [self.navigationController pushViewController:editVC animated:NO];
    
}

- (IBAction)doneBtnAction:(id)sender {
    if (self.selectedArray.count == 0) {
        ShowToastLong(@"至少选择一个");
        return;
    }
    
    [self.navigationController dismissViewControllerAnimated:YES completion:^{
        [XSPhotosManager shareInstance].selectedPhtotosBlock(self.selectedArray);
    }];
}



@end
